package com.xiaohai.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xiaohai.common.R;
import com.xiaohai.projo.Class;
import com.xiaohai.projo.dto.ClassDto;
import com.xiaohai.projo.Teacher;
import com.xiaohai.service.ClassService;
import com.xiaohai.service.TeacherService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xiaohai
 * @since 2024-02-24
 */
@Slf4j
@RestController
@RequestMapping("/class")
public class ClassController {
    @Autowired
    private ClassService classService;

    @Autowired
    private TeacherService teacherService;


    @GetMapping("/list")
    public R<IPage<ClassDto>> list(Integer currentPage, Integer pageSize, String name, @RequestParam("teacher_name") String teacherName, Integer identity, String account) {

        IPage<ClassDto> list = classService.myList(currentPage, pageSize, name, teacherName, identity, account);
        return R.success(list, "获取数据成功");
    }

    @GetMapping
    public R<ClassDto> detail(String id) {
        ClassDto aClass = classService.detail(id);
        if (Objects.isNull(aClass)) {
            return R.error("获取详情失败", 201);
        }
        return R.success(aClass, "获取详情成功");
    }

    @PostMapping
    public R<Objects> addAndUpdate(@RequestBody Class aclass, Integer identity, String account) {
        log.info("identity:{}", identity);
        Integer id = aclass.getId();
        if (id != null) { // 修改

            Boolean b = classService.myUpdate(aclass);
            if (b) {
                return R.success(null, "修改成功");
            }
            return R.error("修改失败", 201);

        } else {
            boolean add = classService.add(aclass, identity, account);
            if (add) {
                return R.success(null, "新增成功");
            }
            return R.error("新增失败", 201);
        }
    }

    @GetMapping("/teacherList")
    public R<List<Teacher>> teacherList() {
        List<Teacher> list = teacherService.list();
        if (Objects.isNull(list)) {
            return R.error("获取数据失败", 201);
        }
        return R.success(list, "获取数据成功");
    }

    @DeleteMapping
    public R<Object> deleteById(Integer id) {
        boolean b = classService.delete(id);
        if (b) {
            return R.success(null, "删除成功");
        }
        return R.error("删除失败,该班级存在学生", 201);
    }

    @PostMapping("/batchAdd")
    public R<Objects> batchAdd(@RequestBody List<Class> aclass, Integer identity) {
        Boolean b = classService.batchAdd(aclass, identity);
        if (b) {
            return R.success(null, "新增成功");
        }
        return R.error("新增失败", 201);
    }
}
